<!DOCTYPE html>
<html>
<head>
  <title>AI 聊天</title>
  <style>
    #chat-container {
      width: 600px;
      height: 400px;
      border: 1px solid #ccc;
      padding: 10px;
      overflow-y: auto;
      margin-bottom: 10px;
    }
    .user-message {
      background-color: #e1f5fe;
      padding: 5px 10px;
      border-radius: 10px;
      margin: 5px 0;
      align-self: flex-end;
    }
    .ai-message {
      background-color: #f5f5f5;
      padding: 5px 10px;
      border-radius: 10px;
      margin: 5px 0;
      align-self: flex-start;
    }
    #message-input {
      width: 500px;
      padding: 5px;
    }
    #send-button {
      padding: 5px 10px;
    }
  </style>
</head>
<body>
  <h1>AI 聊天</h1>
  <div id="chat-container"></div>
  <input type="text" id="message-input" placeholder="输入您的问题...">
  <button id="send-button">发送</button>

  <script>
    const chatContainer = document.getElementById('chat-container');
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');

    // 添加消息到聊天容器
    function addMessage(message, isUser) {
      const messageElement = document.createElement('div');
      messageElement.className = isUser ? 'user-message' : 'ai-message';
      messageElement.textContent = message;
      chatContainer.appendChild(messageElement);
      chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // 发送消息并获取流式响应
    async function sendMessage() {
      const message = messageInput.value.trim();
      if (!message) return;

      // 显示用户消息
      addMessage(message, true);
      messageInput.value = '';

      // 创建AI回复的占位元素
      const aiMessageElement = document.createElement('div');
      aiMessageElement.className = 'ai-message';
      aiMessageElement.textContent = '正在思考...';
      chatContainer.appendChild(aiMessageElement);
      chatContainer.scrollTop = chatContainer.scrollHeight;

      try {
        // 创建 EventSource 连接
        const response = await fetch('/api/ai/chat-stream', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            message: message,
            userId: 10 // 假设用户ID
          })
        });

        if (!response.ok) {
          throw new Error('网络响应不正常');
        }

        // 处理 SSE 响应
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        aiMessageElement.textContent = '';

        let buffer = '';
        
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          
          buffer += decoder.decode(value, { stream: true });
          
          // 处理缓冲区中的所有完整事件
          let eventEnd = buffer.indexOf("\n\n");
          while (eventEnd > -1) {
            const eventData = buffer.substring(0, eventEnd);
            buffer = buffer.substring(eventEnd + 2);
            
            // 解析事件数据
            const eventLines = eventData.split("\n");
            let eventName = '';
            let eventContent = '';
            
            for (const line of eventLines) {
              if (line.startsWith("event: ")) {
                eventName = line.substring(7);
              } else if (line.startsWith("data: ")) {
                eventContent = line.substring(6);
              }
            }
            
            // 处理不同类型的事件
            if (eventName === 'message') {
              aiMessageElement.textContent += eventContent;
              chatContainer.scrollTop = chatContainer.scrollHeight;
            } else if (eventName === 'complete') {
              // 完整消息已接收，可以做一些额外处理
              console.log('完整消息:', eventContent);
            } else if (eventName === 'error') {
              aiMessageElement.textContent = '错误: ' + eventContent;
            }
            
            eventEnd = buffer.indexOf("\n\n");
          }
        }
      } catch (error) {
        console.error('获取AI响应时出错:', error);
        aiMessageElement.textContent = '抱歉，获取回复时出错。';
      }

      chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // 事件监听器
    sendButton.addEventListener('click', sendMessage);
    messageInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') sendMessage();
    });
  </script>
</body>
</html> 